package com.game.fg.service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class FGTimer {
    private static Logger logger = LogManager.getLogger(FGTimer.class.getName());

    private static int curZeroTime;//当前零点时间

    void start() {
        //0.1秒定时器
        new Timer().scheduleAtFixedRate(task, 0, 100);
        //1秒钟定时器
        new Timer().scheduleAtFixedRate(taskSec1, 5000, 1000);
        //60秒定时器
        new Timer().scheduleAtFixedRate(taskSec60, 60000, 60000);
    }


    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
        }
    };
    private TimerTask taskSec1 = new TimerTask() {
        @Override
        public void run() {
            checkZeroTime();
            ReconnectServerTimer();
        }
    };
    private TimerTask taskSec60 = new TimerTask() {
        @Override
        public void run() {
            mysqlKeepAlive();
            AuthServer.getInstance().KeepAlive();
            ManagerServer.getInstance().KeepAlive();
            MQServer.getInstance().KeepAlive();
            ManagerServer.getInstance().updateOnline(FGWebSocket.getOnlineNum());
            optGlobalCoinTimer();
        }
    };

    //日志入库
    private void insertLogTimer() {
        List<FGGame.GameLog> sqlList = FGGame.getUserLog();
        if (sqlList.size() == 0) {
            return;
        }
        DBPool.executeInThread(sqlList, "call p_add_game_log(?,?,?,?,?,?,?,?)");
    }

    //数据库心跳
    private void mysqlKeepAlive() {
        for (int i = 0; i < DBPool.INITIAL_SIZE; i++) {
            DBPool.executeInThread("select 1+1", "");
        }
    }

    //同步奖池到web
    private void optGlobalCoinTimer() {
        double line = 1000;
        //初级奖池同步
        if (FGGame.benefitsOfJunior % line == 2) {
            FGGame.optGlobalCoinPool(2, FGGame.benefitsOfJunior - line, line, 0);
            FGGame.benefitsOfJunior = line;
        }
        //中级奖池同步
        if (FGGame.benefitsOfMiddle % line == 2) {
            FGGame.optGlobalCoinPool(2, FGGame.benefitsOfMiddle - line, line, 1);
            FGGame.benefitsOfMiddle = line;
        }
        //高级奖池同步
        if (FGGame.benefitsOfSenior % line == 2) {
            FGGame.optGlobalCoinPool(2, FGGame.benefitsOfSenior - line, line, 2);
            FGGame.benefitsOfSenior = line;
        }
    }

    //断线重连
    private void ReconnectServerTimer() {
        if (!FGMain.started) {
            return;
        }
        if (AuthServer.getInstance().getWs() == null || AuthServer.getInstance().getWs().isClosed()) {
            AuthServer.getInstance().start(FGConfig.getInstance().getAuthServerUrl());
            logger.warn("重连认证服务器...");
        }
        if (ManagerServer.getInstance().getWs() == null || ManagerServer.getInstance().getWs().isClosed()) {
            ManagerServer.getInstance().start(FGConfig.getInstance().getManagerServerUrl());
            logger.warn("重连管理服务器...");
        }
        if (MQServer.getInstance().getWs() == null || MQServer.getInstance().getWs().isClosed()) {
            MQServer.getInstance().start(FGConfig.getInstance().getMQServerUrl());
            logger.warn("重连MQ服务器...");
        }
    }

    //检测零点时间
    private void checkZeroTime() {
        long current = System.currentTimeMillis();
        int zeroTime = (int) (current / (1000 * 3600 * 24) * (1000 * 3600 * 24) / 1000);
        if (getCurZeroTime() == 0) {
            setCurZeroTime(zeroTime, true);
        }
        if (zeroTime != getCurZeroTime()) {
            //零点
            setCurZeroTime(zeroTime, true);
            logger.debug("零点时间");
            //重置玩家每日相关数据
            Enumeration e = FGUserManager.getInstance().getUserMap().elements();
            while (e.hasMoreElements()) {
                FGUser user = (FGUser) e.nextElement();
                user.setDayHelpCoin(0);
                user.setDayWinLoseScore(0);
                user.setDayTax(0);
            }
            logger.debug("重置玩家每日相关数据");
        }
    }

    private int getCurZeroTime() {
        return curZeroTime;
    }

    void setCurZeroTime(int curZeroTime, boolean writeDb) {
        FGTimer.curZeroTime = curZeroTime;
        if (writeDb) {
            //Jedis redis = FGRedis.getInstance().getJedis();
            //String zeroTimeKey = String.format("CQ:%d:curZeroTime", ManagerServer.serverInfo.serverID);
            //redis.set(zeroTimeKey, String.valueOf(curZeroTime));
        }
    }


    private static FGTimer fgTimer = new FGTimer();

    public static FGTimer getInstance() {
        return fgTimer;
    }
}
